import { setTimeOut } from "../time/SetTime";

/**
 * 配置文件热更新方法
 * @param configfolder 配置文件文件夹
 * @param newScripAdd 配置文件事件
 */
export function hotConfig(configfolder: Instance, newScripAdd: (instance: Instance, old: Instance) => void) {
    let newDevFilsMap: Map<Instance, {
        changeConnect?: RBXScriptConnection;
        change?: RBXScriptConnection
        cloneOne?: Instance
    }> | undefined;
    let changeNewScript: Map<Instance, Instance> | undefined;
    if (game.GetService('RunService').IsStudio()) {
        changeNewScript = new Map();
        newDevFilsMap = new Map();
    }
    const configfolderSearchFun = (c: Instance) => {
        if (changeNewScript?.has(c)) {
            // loginfo?.info('new scriptchange', c)
            // if (c.IsA('ModuleScript')) {
            //     const module = require(c)
            //     loginfo?.info('new module', module)
            // }
            newScripAdd(c, c);
        } else if (game.GetService('RunService').IsStudio()) {

            if (!newDevFilsMap?.has(c))
                newDevFilsMap?.set(c, {});
            const config = newDevFilsMap?.get(c);
            const changeConnect = (c.Changed as RBXScriptSignal).Connect((a, b) => {
                if (a as string === "Parent") return
                if (!config) return
                // print('changed start', config.cloneOne)
                config.change?.Disconnect();
                config.change = setTimeOut(3, () => {
                    print('scripted changed over', config.cloneOne)
                    const newClone = c.Clone();
                    changeNewScript?.set(newClone, newClone)
                    newClone.Parent = c.Parent
                    config.cloneOne?.Destroy();
                    if (config.cloneOne)
                        changeNewScript?.delete(config.cloneOne)
                    config.cloneOne = newClone;
                })

            })
            if (config) {
                config.changeConnect?.Disconnect();
                config.changeConnect = changeConnect
            }

        }

        if (changeNewScript?.has(c)) {

        } else {
            newScripAdd(c, c);
        }


    }
    configfolder.GetDescendants().forEach(c => configfolderSearchFun(c))
    configfolder.DescendantAdded.Connect(c => configfolderSearchFun(c))
}